# this script generates measures of defensive ownership based on JSCReg:
# foreign in chain; offshore in chain

# load the list of countries designated as offshores
offshore_codes <- read_csv("Additional Data/offshore_codes.csv")

# create a list of all foreign firms in the extracted ownership links
foreign_firms <- all.ids %>% 
  filter(entity == "corporate", country != 804) %>% 
  pull(id) %>% unique()
foreign_firms_codes <- all.ids %>%
  filter(entity == "corporate" & country != 804) %>%
  select(id, country, entity_name)

# create a list of firms to check (all firms in JSCReg)
step0_firms <- all.ids %>% 
  filter(step == 0) %>% 
  pull(id) %>% unique()

# create a data frame that will be populated with defensive ownership measures
JSCReg_firms <- all.ids %>% filter(id %in% step0_firms) %>%
  dplyr::select("id", "entity_name", "owner") %>%
  mutate(okpo = as.numeric(substr(id, 3, nchar(id))),
         shortest_path_foreign = NA,
         foreign_owners = NA)

# create a data frame that will be populated with data on foreign owners
# (used in some supplementary analyses)
JSCReg_foreign_owners <- tibble(okpo = as.numeric(), 
                                foreign_owner_name = as.character(), 
                             foreign_owner_country = as.numeric())

# examine paths from foreign firms
for (i in 1:nrow(JSCReg_firms)) {
  firm <- JSCReg_firms$id[i]
  print(paste(i, firm))
  
  # extract paths to foreign firms
  spaths_foreign <- shortest_paths(o.network.D, firm, foreign_firms, mode="in")
  
  # calculate the length of paths to foreign firms
  shortest_path_foreign <- unlist(lapply(spaths_foreign$vpath, length))
  shortest_path_foreign <- 
    ifelse(max(shortest_path_foreign) > 0,
           min(shortest_path_foreign[shortest_path_foreign != 0]-1),
           NA)
  JSCReg_firms$shortest_path_foreign[i] <- shortest_path_foreign
  
  # when path exists, set foreign in chain to 1
  JSCReg_firms$foreign_in_chain[i] <- 1 - is.na(shortest_path_foreign)
  
  # if any of the foreign entities in chain are offshore,
  # set offshore in chain to 1
  foreign_entities <- unique(unlist(lapply(spaths_foreign$vpath, names)))
  foreign_entities <- foreign_entities[foreign_entities %in% foreign_firms]
  foreign_entities_countries <- foreign_firms_codes %>%
    filter(id %in% foreign_entities) %>% 
    pull(country) %>% unique()
  JSCReg_firms$offshore_in_chain[i] <- 
    sum(any(foreign_entities_countries %in% offshore_codes$country_code))
  
  # update the data frame with foreign owners
  if (length(foreign_entities) > 0) {
    firm_foreign_owners <- tibble(okpo = as.numeric(substr(firm, 3, nchar(firm))),
                                  id = foreign_entities) %>%
      left_join(foreign_firms_codes) %>%
      select(-id) %>%
      rename(foreign_owner_name = entity_name,
             foreign_owner_country = country)
    JSCReg_foreign_owners <- bind_rows(JSCReg_foreign_owners, firm_foreign_owners)
  }
}

# add dummy: whether a firm has owners in the network graph
has_owners <- all.ids %>% select(id) %>%
  mutate(has_owners = if_else(id %in% all.edges$sub, 1, 0))
JSCReg_firms <- left_join(JSCReg_firms, has_owners)

JSCReg_firms <- JSCReg_firms %>%
  select(-c(id, foreign_owners, owner))

# save data
write_dta(JSCReg_firms, paste0("Network Data/JSCReg_hiding_", 
                                    search_date, ".dta"), label = NULL)
write_dta(JSCReg_foreign_owners, 
          paste0("Network Data/JSCReg_foreign_owners_", 
                 search_date, ".dta"))
